package com.example.wenqujingdian.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.wenqujingdian.R;
import com.example.wenqujingdian.api.Contants;
import com.example.wenqujingdian.model.AudioLocalDetailBean;
import com.example.wenqujingdian.utils.GlideAudioImageLoader;
import com.example.wenqujingdian.utils.ToastUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

public class AudioLocalPlayActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.title)
    TextView mTitle;
    @BindView(R.id.banner)
    Banner banner;

    private ImageView play/*, stop, ivv*/;
    private TextView musicLength, musicCur;
    private SeekBar seekBar;
    private RelativeLayout bac_audio;

    private MediaPlayer mediaPlayer;

    private Timer timer;

    private boolean isSeekBarChanging;//互斥变量，防止进度条与定时器冲突。
    private int currentPosition;//当前音乐播放的进度

    SimpleDateFormat format;

    private boolean isPause = false;//是否暂停
    private boolean isFirst = false;//diyici

    private int index;

    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_play);
        ButterKnife.bind(this);
        if (getIntent() != null){
            path = getIntent().getStringExtra("path");
        }
        AudioLocalDetailBean listBean = Contants.localPlayAudioList.get(index);
        String audioTitle = listBean.getAudioTitle();
        mTitle.setText(audioTitle);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initView();
    }

    private void initView() {

        format = new SimpleDateFormat("mm:ss");

        play = findViewById(R.id.play);
//        stop = findViewById(R.id.stop);

        musicLength = (TextView) findViewById(R.id.music_length);
        bac_audio = findViewById(R.id.bac_audio);
        musicCur = (TextView) findViewById(R.id.music_cur);
//        ivv = findViewById(R.id.ivvv);

        seekBar = (SeekBar) findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(new MySeekBar());

        play.setOnClickListener(this);
//        stop.setOnClickListener(this);

        if (findViewById(R.id.tv_land) != null) {
            int[] imageId = {R.drawable.bg1, R.drawable.bg2, R.drawable.bg3, R.drawable.bg4, R.drawable.bg5};
            setBanner(imageId);
        } else {
            int[] imageId2 = {R.drawable.bgh1, R.drawable.bgh2, R.drawable.bgh3, R.drawable.bgh4, R.drawable.bgh5, R.drawable.bgh6};
            setBanner(imageId2);
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            initMediaPlayer();//初始化mediaplayer
        }
    }


    private void setBanner(int[] imageId) {
        List<Integer> images = new ArrayList<>();
        for (int id : imageId) {
            images.add(id);
        }
//        //设置banner样式
        banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideAudioImageLoader());
        //设置图片集合
        banner.setImages(images);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置标题集合（当banner样式有显示title时）
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(6000);
//        //设置指示器位置（当banner模式中有指示器时）
//        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.start();
    }

    private void initMediaPlayer() {
        try {
            if (mediaPlayer == null)
                mediaPlayer = new MediaPlayer();
//            mediaPlayer.setDataSource("/sdcard/music.mp3");//指定音频文件的路径
            mediaPlayer.setDataSource(path + Contants.localPlayAudioList.get(index).getAudioUrl());//指定音频文件的路径
            mediaPlayer.prepare();//让mediaplayer进入准备状态
            mediaPlayer.setLooping(false);

//            play.setImageResource(R.mipmap.ic_play_btn_play_pressed);
//
//            mediaPlayer.seekTo(currentPosition);

            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                public void onPrepared(MediaPlayer mp) {
                    seekBar.setMax(mediaPlayer.getDuration());
                    startTimer();
                    musicLength.setText(format.format(mediaPlayer.getDuration()) + "");
                    musicCur.setText("00:00");
                    mediaPlayer.start();//开始播放
                }
            });

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    try {
                        if (index != Contants.localPlayAudioList.size() - 1) {
                            AudioLocalDetailBean listBean = Contants.localPlayAudioList.get(++index);
                            mTitle.setText(listBean.getAudioTitle());
                            mediaPlayer.reset();
                            mediaPlayer.setDataSource(path + listBean.getAudioUrl());//指定音频文件的路径
                            mediaPlayer.prepare();//让mediaplayer进入准备状态
                            mediaPlayer.setLooping(false);
                            play.setImageResource(R.mipmap.ic_play_btn_play_pressed);
                            mediaPlayer.seekTo(currentPosition);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 &&
                        grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initMediaPlayer();
                } else {
                    ToastUtil.show("拒绝使用");
                    finish();
                }
                break;
            default:
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.play:
                if (!isFirst) {
                    isFirst = true;
                    if (!mediaPlayer.isPlaying()) {
                        play.setImageResource(R.mipmap.ic_play_btn_play_pressed);
                        mediaPlayer.start();//开始播放
                        mediaPlayer.seekTo(currentPosition);
//                        startTimer();
                    } else {
                        mediaPlayer.pause();//暂停播放
                        play.setImageResource(R.mipmap.ic_play_btn_pause_pressed);
                    }
                } else {
                    if (!isPause) {
                        isPause = true;
                        mediaPlayer.pause();//暂停播放
                        play.setImageResource(R.mipmap.ic_play_btn_play_pressed);
                    } else {
                        isPause = false;
                        mediaPlayer.start();//播放
                        play.setImageResource(R.mipmap.ic_play_btn_pause_pressed);
                    }
                }

                break;
//            case R.id.stop:
//                if (mediaPlayer.isPlaying() || isPause) {
//                    isFirst = false;
//                    isPause = false;
//                    play.setImageResource(R.mipmap.ic_play_btn_play_pressed);
//                    mediaPlayer.reset();//停止播放
//                    initMediaPlayer();
//                }
//                break;
        }
    }

    private void startTimer() {
        //监听播放时回调函数
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {

            Runnable updateUI = new Runnable() {
                @Override
                public void run() {
                    if (timer == null) return;
                    musicCur.setText(format.format(mediaPlayer.getCurrentPosition()) + "");
                }
            };

            @Override
            public void run() {
                if (!isSeekBarChanging) {
                    seekBar.setProgress(mediaPlayer.getCurrentPosition());
                    runOnUiThread(updateUI);
                }
            }
        }, 0, 50);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isSeekBarChanging = true;
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    /*进度条处理*/
    public class MySeekBar implements SeekBar.OnSeekBarChangeListener {

        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
        }

        /*滚动时,应当暂停后台定时器*/
        public void onStartTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = true;
        }

        /*滑动结束后，重新设置值*/
        public void onStopTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = false;
            mediaPlayer.seekTo(seekBar.getProgress());
        }
    }
}
